#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

class ImageExtractor {
    constructor() {
        this.outputDir = 'extracted-images';
        this.jsonFile = 'generate.json';
    }

    parseArgs() {
        const args = process.argv.slice(2);
        const options = {
            input: 'generate.json',
            output: 'extracted-images',
            format: 'png',
            prefix: 'image',
            verbose: false,
            help: false
        };

        for (let i = 0; i < args.length; i++) {
            switch (args[i]) {
                case '-i':
                case '--input':
                    options.input = args[++i];
                    break;
                case '-o':
                case '--output':
                    options.output = args[++i];
                    break;
                case '-f':
                case '--format':
                    options.format = args[++i];
                    break;
                case '-p':
                case '--prefix':
                    options.prefix = args[++i];
                    break;
                case '-v':
                case '--verbose':
                    options.verbose = true;
                    break;
                case '-h':
                case '--help':
                    options.help = true;
                    break;
            }
        }

        return options;
    }

    showHelp() {
        console.log(`
图片提取工具 - 从 JSON 文件中提取 base64 编码的图片

使用方法:
  node extract-images.js [选项]

选项:
  -i, --input <file>    输入 JSON 文件 (默认: generate.json)
  -o, --output <dir>    输出目录 (默认: extracted-images)
  -f, --format <ext>    输出格式 (默认: png)
  -p, --prefix <name>   文件名前缀 (默认: image)
  -v, --verbose         显示详细信息
  -h, --help           显示帮助信息

示例:
  node extract-images.js
  node extract-images.js -i response.json -o images
  node extract-images.js -p photo -f jpg -v
        `);
    }

    ensureDirectory(dir) {
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
            return true;
        }
        return false;
    }

    getFileExtension(mimeType) {
        const mimeMap = {
            'image/png': 'png',
            'image/jpeg': 'jpg',
            'image/jpg': 'jpg',
            'image/gif': 'gif',
            'image/webp': 'webp',
            'image/bmp': 'bmp',
            'image/svg+xml': 'svg'
        };
        return mimeMap[mimeType] || 'png';
    }

    extractImages(options) {
        try {
            console.log(`\n📂 读取文件: ${options.input}`);

            if (!fs.existsSync(options.input)) {
                throw new Error(`文件不存在: ${options.input}`);
            }

            const fileContent = fs.readFileSync(options.input, 'utf8');
            const data = JSON.parse(fileContent);

            if (!data.data || !data.data.images || !Array.isArray(data.data.images)) {
                throw new Error('JSON 格式无效: 未找到 data.images 数组');
            }

            const images = data.data.images;
            console.log(`✨ 找到 ${images.length} 张图片\n`);

            const dirCreated = this.ensureDirectory(options.output);
            if (dirCreated) {
                console.log(`📁 创建输出目录: ${options.output}`);
            }

            const results = [];

            images.forEach((image, index) => {
                try {
                    if (!image.base64) {
                        console.warn(`⚠️  图片 ${index + 1} 缺少 base64 数据，跳过`);
                        return;
                    }

                    const extension = image.mimeType ?
                        this.getFileExtension(image.mimeType) :
                        options.format;

                    const fileName = `${options.prefix}-${(index + 1).toString().padStart(3, '0')}.${extension}`;
                    const filePath = path.join(options.output, fileName);

                    const buffer = Buffer.from(image.base64, 'base64');

                    if (buffer.length === 0) {
                        console.warn(`⚠️  图片 ${index + 1} base64 解码失败，跳过`);
                        return;
                    }

                    fs.writeFileSync(filePath, buffer);

                    const fileSize = (buffer.length / 1024).toFixed(2);

                    results.push({
                        index: index + 1,
                        fileName,
                        size: fileSize,
                        mimeType: image.mimeType || 'unknown'
                    });

                    if (options.verbose) {
                        console.log(`  [${index + 1}/${images.length}] ${fileName} (${fileSize} KB)`);
                    }

                } catch (err) {
                    console.error(`❌ 处理图片 ${index + 1} 时出错: ${err.message}`);
                }
            });

            console.log(`\n✅ 成功提取 ${results.length}/${images.length} 张图片`);
            console.log(`📍 保存位置: ${path.resolve(options.output)}\n`);

            if (results.length > 0) {
                console.log('📊 提取结果:');
                console.log('─'.repeat(60));
                results.forEach(r => {
                    console.log(`  ${r.fileName.padEnd(20)} ${r.size.padStart(10)} KB  ${r.mimeType}`);
                });
                console.log('─'.repeat(60));

                const totalSize = results.reduce((sum, r) => sum + parseFloat(r.size), 0);
                console.log(`  总计: ${results.length} 个文件, ${totalSize.toFixed(2)} KB\n`);
            }

            return results;

        } catch (error) {
            console.error(`\n❌ 错误: ${error.message}\n`);
            if (options.verbose) {
                console.error('详细错误信息:', error);
            }
            process.exit(1);
        }
    }

    run() {
        const options = this.parseArgs();

        if (options.help) {
            this.showHelp();
            return;
        }

        console.log('🎨 图片提取工具 v1.0.0');
        console.log('─'.repeat(60));

        this.extractImages(options);
    }
}

if (require.main === module) {
    const extractor = new ImageExtractor();
    extractor.run();
}

module.exports = ImageExtractor;